import React from 'react';
import { inject, observer } from 'mobx-react';
import { WeaLocaleProvider, WeaRightMenu, WeaNewScroll, WeaInput, WeaBrowser, WeaTextarea, WeaAlertPage, WeaTagGroup, WeaDatePicker, WeaCheckbox, WeaDialog } from 'ecCom';
import { Row, Button, Col, Input, Select, Icon, Spin, Modal } from 'antd';
import { observable, action, toJS } from 'mobx';
import Collapse from '../../public/collapse.js';
import sendApi from '../../apis/sendSms';
import AlertModal from '../../public/AlertModal';
import SmsTempList from '../SmsTemplate/TempList';
import moment from 'moment';

const Option = Select.Option;
const getLabel = WeaLocaleProvider.getLabel;
const confirm = Modal.confirm;

@inject('sendSmsStore')
@inject('smsTempStore')
@inject('smsRegularStore')
@observer
class ViewRegularSms extends React.Component {
	constructor(props) {
		super(props);
		this.state = {
			showAddBtn: true,
			showTemp: false,
			clickFlag: true,
			regularDateTime: moment().format('YYYY-MM-DD HH:MM'),
			visible: false,
		};
	}
	componentDidMount() {

	}
	componentWillReceiveProps(nextProps) {
		const { smsRegularStore } = nextProps;
		this.setState({ visible: nextProps.visible });
	}

	getDialogBtn = () => {
		const { sendSmsStore } = this.props;
		const { receiverType, sendStatus, loading } = sendSmsStore;
		let btns = [];
		(sendStatus == '1' || sendStatus == '2') && btns.push(
			<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@3myuyr@saveBtn`}
  type="primary"
  loading={loading}
  onClick={() => {
					this.onRightMenuClick('0');
				}}
			>{getLabel(86, '保存')}</Button>,
		);
		sendStatus == '1' && btns.push(
			<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@14wepq@sendBtn`}
  type="primary"
  loading={loading}
  onClick={() => {
					this.onRightMenuClick('1');
				}}
			>{getLabel(519185, '立即发送')}</Button>,
		);
		sendStatus == '2' && btns.push(
			<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@ep9ry2@sendContinueBtn`}
  type="primary"
  loading={loading}
  onClick={() => {
					this.onRightMenuClick('3');
				}}
			>{getLabel(519187, '继续发送')}</Button>,
		);
		sendStatus == '3' && btns.push(
			<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@nbr7ob@sendStopBtn`}
  type="primary"
  loading={loading}
  onClick={() => {
					this.onRightMenuClick('2');
				}}
			>{getLabel(519186, '暂停发送')}</Button>,
		);
		return btns;
	}

	getRightMenu() {
		const { sendSmsStore } = this.props;
		const { receiverType, sendStatus } = sendSmsStore;
		let btns = [];
		(sendStatus == '1' || sendStatus == '2') && btns.push({
			key: '0',
			icon: <i className="icon-coms-Approval" />,
			content: getLabel(86, '保存'),
			onClick: () => {
				this.onRightMenuClick('0');
			},
		});
		sendStatus == '1' && btns.push({
			key: '1',
			icon: <i className="icon-coms-Approval" />,
			content: getLabel(519185, '立即发送'),
			onClick: () => {
				this.onRightMenuClick('1');
			},
		});
		sendStatus == '3' && btns.push({
			key: '2',
			icon: <i className="icon-coms-Approval" />,
			content: getLabel(519186, '暂停发送'),
			onClick: () => {
				this.onRightMenuClick('2');
			},
		});
		sendStatus == '2' && btns.push({
			key: '3',
			icon: <i className="icon-coms-Approval" />,
			content: getLabel(519187, '继续发送'),
			onClick: () => {
				this.onRightMenuClick('3');
			},
		});
		return btns;
	}

	// 右键菜单事件绑定
	onRightMenuClick(key) {
		const { smsRegularStore } = this.props;
		const { setLoading, msg, regularDateTime, receiverType } = this.props.sendSmsStore;
		const { sendSmsStore } = this.props;
		let param = { msg: sendSmsStore.msg, regularDateTime };
		if (receiverType != '1' && !sendSmsStore.msg) {
			AlertModal(getLabel(384506, '短信内容不能为空！'));
			return;
		}
		// 关闭前端时间必填项校验 by Iverson
		// if (!regularDateTime) {
		// 	AlertModal(getLabel(506448, '定时发送时间不能为空'));
		// 	return;
		// }
		let _that = this;
		if (key == '0') { // 保存
			this.saveSmsRegularInfo();
		}

		if (key == '1') { // 立即发送
			confirm({
				title: getLabel(131329, '信息确认'),
				content: getLabel(519609, '确定立即发送？'),
				onOk() {
					_that.sendSmsRegular();
				},
				onCancel() {

				},
			});
		}

		if (key == '2') { // 暂停发送
			confirm({
				title: getLabel(131329, '信息确认'),
				content: getLabel(519610, '确定暂停发送？'),
				onOk() {
					_that.stopSmsRegular();
				},
				onCancel() {

				},
			});
		}
		if (key == '3') { // 继续发送
			confirm({
				title: getLabel(131329, '信息确认'),
				content: getLabel(519611, '确定继续发送？'),
				onOk() {
					_that.sendSmsRegular();
				},
				onCancel() {

				},
			});
		}
	}

	saveSmsRegularInfo = () => {
		const { smsRegularStore, sendSmsStore } = this.props;
		const { regularSmsId, closeRegularSmsInfo, doSearch } = smsRegularStore;
		const { msg, regularDateTime, setLoading } = sendSmsStore;
		let param = { msg: sendSmsStore.msg, regularDateTime, id: regularSmsId };
		setLoading(true);
		let ret = smsRegularStore.saveSmsRegularInfo(param);
		Promise.all([ret]).then((result) => {
			closeRegularSmsInfo();
			doSearch();
			setLoading(false);
		});
	}

	sendSmsRegular = () => {
		const { smsRegularStore, sendSmsStore } = this.props;
		const { regularSmsId, closeRegularSmsInfo, doSearch } = smsRegularStore;
		const { msg, regularDateTime, setLoading } = sendSmsStore;
		let param = { msg: sendSmsStore.msg, regularDateTime, id: regularSmsId, receiverType: sendSmsStore.receiverType, fromDialog: 1 };
		setLoading(true);
		let ret = smsRegularStore.sendSmsRegular(param);
		Promise.all([ret]).then((result) => {
			closeRegularSmsInfo();
			doSearch();
			setLoading(false);
		});
	}

	stopSmsRegular = () => {
		const { smsRegularStore, sendSmsStore } = this.props;
		const { regularSmsId, closeRegularSmsInfo, doSearch } = smsRegularStore;
		const { msg, regularDateTime, setLoading } = sendSmsStore;
		let param = { msg: sendSmsStore.msg, regularDateTime, id: regularSmsId };
		setLoading(true);
		let ret = smsRegularStore.stopSmsRegular(param);
		Promise.all([ret]).then((result) => {
			closeRegularSmsInfo();
			doSearch();
			setLoading(false);
		});
	}

	render() {
		const { sendSmsStore } = this.props;
		const { receiverType } = sendSmsStore;
		const collectParams = {
			favname: `${getLabel('519174', '定时发送短信列表')}`,
			objid: 0,
			link: 'wui/index.html#/main/sms/smsRegular',
			importantlevel: 1,
		};
		let dialogHeight = receiverType == '0' ? 500 : receiverType == '1' ? 200 : 470;
		let dialogWidth = receiverType == '1' ? 600 : 900;
		return (<WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@9njh0t`}
  visible={this.state.visible}
  title={getLabel(519549, '编辑短信')}
  icon="icon-coms-message"
  iconBgcolor="#0079de"
  className="createWorkPlan"
  buttons={this.getDialogBtn()}
  moreBtn={{
				datas: this.getRightMenu(),
				collectParams,
			}}
  style={{ width: dialogWidth, height: dialogHeight }}
  onCancel={this.doClose}
		>
			<div className="sms-editSms" style={{ height: '100%' }} onClick={this.pageClick.bind(this)}>
				<SmsTempList ecId={`${this && this.props && this.props.ecId || ''}_SmsTempList@eabbah`}
  visible={sendSmsStore.showFlag}
  doRefresh={this.doRefresh}
  doClose={() => {
						sendSmsStore.closeTempList();
					}}
				/>
				{sendSmsStore.hasRight === '1' &&
					<WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@zxzrua`} datas={this.getRightMenu()} >
						{this.getEditSms()}
					</WeaRightMenu>
				}
				{sendSmsStore.hasRight === '0' && <WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@gbw2bm`} top={'36%'}>
					<div>
						{getLabel(2012, '对不起，您暂时没有权限！')}
					</div>
				</WeaAlertPage>}
			</div>
		</WeaDialog>
		);
	}
	validate(v) { // 验证通过返回false 不通过返回true
		//	var regex = /^((\+)?86|((\+)?86)?)0?1[34578]\d{9}$/;
		let regex = /^[\d-\+]*$/;
		let ret = !regex.test(v);
		return ret;
	}
	getEditSms() {
		const { sendSmsStore } = this.props;
		const { receiverType, sendStatus } = sendSmsStore;
		let crmIdsBrowserParam = {
			hasAddBtn: false,
			hasAdvanceSerach: true,
			isAutoComplete: 1,
			isDetail: 0,
			isMultCheckbox: false,
			isSingle: false,
			linkUrl: '/spa/crm/static/index.html#/main/crm/contacterView?contacterId=',
			quickSearchName: '',
			title: getLabel(17129, '客户联系人'),
			type: '67',
			viewAttr: 1,
		};
		let viewAttr = (sendStatus == '1' || sendStatus == '2') ? 3 : 1;
		let offset = 4;
		let titlecol = 4;
		let fieldcol = 10;
		let marginBottomValue = 16;
		const contentStyle = {
			display: this.state.showTemp ? 'block' : 'none',
		};
		if (sendSmsStore.sendCrm) {
			crmIdsBrowserParam = { ...crmIdsBrowserParam, ...{ replaceDatas: toJS(sendSmsStore.sendCrm) } };
		}

		if (!this.state.showAddBtn) contentStyle['border-bottom'] = 0;

		return (
			<div style={{ height: '100%' }} className="">
				{receiverType == '0' && <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@23umks`} className="" style={{ marginBottom: `${marginBottomValue}px`, paddingTop: `${marginBottomValue}px` }}>
					<Col ecId={`${this && this.props && this.props.ecId || ''}_Col@3w5vyg`} offset={offset} span={titlecol} >
						<span>{getLabel(32926, '短信接收员工')}: </span>
					</Col>
					<Col ecId={`${this && this.props && this.props.ecId || ''}_Col@ppkso5`} span={fieldcol} style={{ marginLeft: '43px' }}>
						<WeaTagGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaTagGroup@eb5s6j`} ref="number_field" splitChar="," viewAttr={1} noDefault={true} validate={this.validate.bind(this)} datas={toJS(sendSmsStore.sendHrm)} />
					</Col>
				</Row>}
				{receiverType == '0' && <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@uzwq61`} className="" style={{ marginBottom: `${marginBottomValue}px` }}>
					<Col ecId={`${this && this.props && this.props.ecId || ''}_Col@xdai10`} offset={offset} span={titlecol} >
						<span>{getLabel(32928, '短信接收客户联系人')}: </span>
					</Col>
					<Col ecId={`${this && this.props && this.props.ecId || ''}_Col@a5en0p`} span={fieldcol} style={{ marginLeft: '43px' }}>
						<WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@jpnrrg`}
  {...crmIdsBrowserParam}
  onChange={(ids, names, datas) => this.onChangeBrowser(ids, names, datas, 'crmIds')}
						/>
					</Col>
				</Row>}


				{(receiverType == '0' || receiverType == '2') && <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@enhrsb`} className={`regularRow-${receiverType}`} style={{ marginBottom: `${marginBottomValue}px` }}>
					<Col ecId={`${this && this.props && this.props.ecId || ''}_Col@zhw9ct`} offset={offset} span={titlecol} style={{ lineHeight: '32px' }}>
						<span >{getLabel(18529, '短信内容')}: </span>
					</Col>
					<Col ecId={`${this && this.props && this.props.ecId || ''}_Col@6cj775`} span={fieldcol} style={{ marginLeft: '43px' }}>
						{(sendStatus == '1' || sendStatus == '2') && <div className="msg-tool"><div style={{ marginTop: '5px', display: 'inline-block' }}>{getLabel(20074, '你已输入')} {sendSmsStore.msgCount || 0} {getLabel(20075, '个字符')}</div>
							<div style={{ float: 'right', marginTop: '5px', marginRight: '20px', display: 'inline-block' }}>
								<div style={{ display: 'inline-block' }}>
									<div className="temp-btn" onClick={this.showTemp}>
										{getLabel(28049, '短信模板')}
									</div>
									<div className="temp-content" style={contentStyle}>
										<div className="arrow1" />
										<div className="arrow2" />
										<div className="temp-list">
											{sendSmsStore.groups.length > 0 &&
												<WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@4kz34x`} height={120}>
													<ul>
														{
															sendSmsStore.groups.map(item => (<li onClick={this.checkTemp.bind(this, item)}>
																	<span>{item.title}</span>
																</li>))
														}
													</ul>
												</WeaNewScroll>
											}
										</div>
										<div className="temp-foot-btn" title={getLabel(611, '添加')} onClick={this.doAdd} >
											<Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@m6ailk`} type="plus-circle-o" />
										</div>
									</div>
								</div>
								<div className="icon-coms-currency setting-btn" title={getLabel(518871, '短信模板维护')} onClick={this.openTempList} />
							</div>
						</div>}
						<WeaTextarea ecId={`${this && this.props && this.props.ecId || ''}_WeaTextarea@ec85jv`} viewAttr={viewAttr} ref="textArea" minRows={8} value={sendSmsStore.msg || ''} onChange={value => this.onChange(value, 'msg')} />
					</Col>
				</Row>}
				{(sendSmsStore.showReply && (receiverType == '0' || receiverType == '2')) &&
					<Row ecId={`${this && this.props && this.props.ecId || ''}_Row@98cmcn`} className="tip-msg" style={{ marginBottom: `${marginBottomValue}px` }}>
						<Col ecId={`${this && this.props && this.props.ecId || ''}_Col@mwebjt`} offset={offset} span={titlecol} style={{ paddingLeft: '40px', paddingTop: `${marginBottomValue}px` }} />
						<Col ecId={`${this && this.props && this.props.ecId || ''}_Col@8q6yfr`} span={fieldcol} style={{ marginLeft: '43px' }}>
							<span>{getLabel(384501, '回复方法：回复 ID+R+回复内容 （ID从收到的短信中可以获得')}</span><br />
							<span>{getLabel(384502, '例如：收到短信为：')} &nbsp; {getLabel(384503, '收到的消息内容(86)')} </span><br />
							<span style={{ paddingLeft: '34px' }}>{getLabel(384504, '回复应该为：')} &nbsp; {getLabel(384505, '86R 发送的消息内容')}</span>
						</Col>
					</Row>}
				<Row ecId={`${this && this.props && this.props.ecId || ''}_Row@u68vge`} className={`regularRow-${receiverType}`} style={{ marginBottom: `${marginBottomValue}px` }}>
					<Col ecId={`${this && this.props && this.props.ecId || ''}_Col@fgvfp9`} offset={offset} span={titlecol} style={{ lineHeight: '32px' }}>
						<span >{getLabel(32028, '定时发送')}: </span>
					</Col>
					<Col ecId={`${this && this.props && this.props.ecId || ''}_Col@fssqzk`} span={fieldcol} style={{ marginLeft: '43px' }}>
						<div className={'regularChk'}>
							<WeaDatePicker ecId={`${this && this.props && this.props.ecId || ''}_WeaDatePicker@pm3je3`}
  // viewAttr={viewAttr}
  showTime={{ format: 'HH:mm' }}
  format="yyyy-MM-dd HH:mm"
  value={sendSmsStore.regularDateTime}
  onChange={value => this.onChange(value, 'regularDateTime')}
							/>
						</div>
					</Col>
				</Row>
			</div>
		);
	}

	getTopButtons() {
		const { loading } = this.props.sendSmsStore;
		let btns = [<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@7lqjim@sendBtn_TopButtons`} type="primary" disabled={loading} onClick={() => { this.onRightMenuClick(0); }}>{getLabel(2083, '发送')}</Button>];
		return btns;
	}

	onChange = (values, type) => {
		const { sendSmsStore } = this.props;
		if (type == 'msg') {
			sendSmsStore.setMsg(values);
		} else if (type == 'regularDateTime') {
			sendSmsStore.setRegularDateTime(values);
		} else {
			this.setState({ [type]: values });
		}
	}

	onChangeBrowser = (ids, names, datas, type) => {
		const { sendSmsStore } = this.props;
		sendSmsStore.setCrm(ids, datas);
	}

	checkTemp = (item) => {
		const { sendSmsStore } = this.props;
		this.refs.textArea.setValue(item.content);
	}

	doAdd = (e) => {
		const { smsTempStore: { showTempDataAndMsg, setDataId } } = this.props;
		setDataId('');
		showTempDataAndMsg();
		e.stopPropagation();
	}

	openTempList = () => {
		const { sendSmsStore, smsTempStore } = this.props;
		smsTempStore.doLoading();
		sendSmsStore.openTempList();
	}

	showTemp = () => {
		this.setState({ showAddBtn: true });
		if (this.state.showTemp) {
			this.setState({ showTemp: false });
		} else {
			this.setState({ showTemp: true });
		}
	}

	pageClick = () => {
		if (this.state.clickFlag) {
			if (this.state.showTemp) {
				this.setState({ showTemp: false });
			}
		}
		this.setState({ clickFlag: true });
	}

	tempClick = (e) => {
		e.stopPropagation();
	}

	doRefresh = () => {
		const { sendSmsStore } = this.props;
		sendSmsStore.getOptions();
	}

	doClose = () => {
		this.props.doClose && this.props.doClose();
	}
}

export default ViewRegularSms;
